package cn.ecnu.auction.dao;


import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.json.JSONArray;

import ToolPackage.Json;

import cn.ecnu.auction.db.DbConnection;
import cn.ecnu.auction.po.Bid;

public class BidDAO {
	
private static Logger logger = Logger.getLogger(GoodsDAO.class);
	
	/**
	 * 竞拍出价
	 * @param gid 拍卖品id
	 * @param bidPrice 竞拍价
	 * @param uid 拍卖品提供者
	 * @result result=1 竞拍成功 result = 0 出价过低  result = -1 错误
	 */
	public int addPurchase(int gid, double bidPrice, int uid){
		Connection conn = DbConnection.getConnection();
		int result = 0;
		double currentPrice=getCurrentPrice(gid);
		if(currentPrice>=bidPrice)
			result=0;
		else
			result=1;
		
		String sql = "insert into bid(bid_id, uid, gid, bidPrice, '%" + result + "%') values(null, ?, ?, ?, ?)";
		
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, uid);
			pstmt.setInt(2, gid);
			pstmt.setDouble(3, bidPrice);
			pstmt.setInt(4, result);
			
			logger.info(pstmt);
			result = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			result = -1;
		} finally {
			DbConnection.closeConnection(conn);
		}
		return result;
	}
	
	/**
	 * 查询最高拍卖价
	 * @param gid 拍卖品id
	 * @return currentPrice 现在价格
	 */
	private double getCurrentPrice(int gid){
		
		double price=0;
		Connection conn = DbConnection.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select currentPrice from goods where gid like '%" + gid + "%'";
		try {
			pstmt=conn.prepareStatement(sql);
			logger.info(pstmt);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				price = rs.getDouble("num");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		} finally {
			DbConnection.closeConnection(conn);
		}
		return price;
	}
	
	
	/**
	 * 
	 * 
	 */
	//public JSONArray getPurchasing()
	{
		//return
	}
	 

}
